<template>
  <base-load-page :loadState="false" class="base-load-page">
    <template #head>
      <div style="padding-bottom: 15px" class="head-box">
        <div class="left-box">
          <base-date-picker
            v-model="dataRange"
            valueFormat="YYYY-MM-DD"
            format="YYYY-MM-DD"
            type="daterange"
            startPlaceholder="开始日期"
            endPlaceholder="结束日期"
            style="flex-grow: 0; width: 350px"
            clearable
            @change="getAxiosData(true)"
          ></base-date-picker>
          <base-input-search
            v-model="filterData.createName"
            clearable
            placeholder="投放人"
            style="width: 230px"
            :prefixIcon="IconSearch"
            @submit="getAxiosData(true)"
          ></base-input-search>
        </div>
      </div>
    </template>
    <div class="page-contnet">
      <div class="statistics-block">
        <div v-for="i in statisticsData" :key="i.flag" class="statistics">
          <div class="title">{{ i.name }}</div>
          <div class="value">{{ i.format(statCostTotal) }}</div>
        </div>
      </div>
      <el-table
        ref="elTableRef"
        v-loading="baseData.loading"
        border
        height="100%"
        :data="tableData"
        showOverflowTooltip
        stripe
        style="width: 100%"
        @sort-change="sortChangeHandel"
      >
        <template #empty>
          <base-empty :description="description" :pageLoadButton="[{ text: '重新加载', callBack: () => getAxiosData() }]"></base-empty>
        </template>
        <el-table-column label="投放时间" prop="thatdayDate" minWidth="120"></el-table-column>
        <el-table-column label="投放人" prop="createName" minWidth="120"></el-table-column>
        <el-table-column label="投放数量" prop="promotion_num" minWidth="120" sortable="custom">
          <template #default="{ row }">
            <span>{{ row.promotionNum }}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <template #foot>
      <div class="pagination-box">
        <el-pagination
          v-model:currentPage="filterData.current"
          v-model:pageSize="filterData.size"
          :pageSizes="[20, 30, 40, 50]"
          :disabled="baseData.loading"
          :pagerCount="13"
          layout="total, prev, pager, next, sizes, jumper"
          :total="baseData.total"
          @change="getAxiosData(true)"
        ></el-pagination>
      </div>
    </template>
  </base-load-page>
</template>

<script setup lang="ts">
  import IconSearch from '~icons/ep/search';
  import { type OceMaterialRecordItem, type OceMaterialRecordReq, ocePromotionAddEverydayCensus } from '@/api/marketing-management';
  import { formatNumberWithMoney } from '@/utils/numb';

  const { proxy } = getCurrentInstance() as any;

  const elTableRef: $RefComp<'ElTable'> = ref(null);
  const baseData = shallowReactive({
    type: 'add' as 'add' | 'edit',
    /** 加载状态 */
    loading: true,
    /** 总数量 */
    total: 0,
  });
  const dataRange = ref<[string, string] | undefined>();
  const filterData = ref<OceMaterialRecordReq>({
    current: 1,
    size: 40,
    startDate: '',
    endDate: '',
    createName: '',
  });

  const tableData: Ref<OceMaterialRecordItem[]> = ref([]);
  const description = ref('');

  onMounted(() => {
    // filterData.value.currentDate = proxy.$dayjs().format('YYYY-MM-DD');
    dataRange.value = [proxy.$dayjs().subtract(1, 'day').format('YYYY-MM-DD'), proxy.$dayjs().subtract(1, 'day').format('YYYY-MM-DD')];
    getAxiosData();
  });

  /** 重置 */
  function initPageData() {
    tableData.value = [];
  }

  const statCostTotal = ref();

  /**
   * 设置表格数据
   */
  async function getAxiosData(showLoading = true) {
    if (Array.isArray(dataRange.value) && dataRange.value.length) {
      filterData.value.startDate = dataRange.value[0];
      filterData.value.endDate = dataRange.value[1];
    } else {
      filterData.value.startDate = '';
      filterData.value.endDate = '';
    }
    try {
      await nextTick();
      baseData.loading = Boolean(showLoading);
      const res = (await ocePromotionAddEverydayCensus(filterData.value)) as any;
      if (res.data) {
        tableData.value = res.data.page.records;
        filterData.value.current = res.data.page.current;
        filterData.value.size = res.data.page.size;
        baseData.total = res.data.page.total;
        statCostTotal.value = res.data.totalNum;
      } else {
        description.value = '暂无数据';
        initPageData();
      }
      baseData.loading = false;
    } catch (error) {
      baseData.loading = false;
      initPageData();
      description.value = error.msg || '加载失败，-BD001';
    }
  }

  interface StatisticsItem {
    name: string;
    flag: 'totalNum';
    type?: string;
    format: (val: string) => number | string;
  }

  const statisticsData = ref<StatisticsItem[]>([
    {
      name: '投放总数量',
      flag: 'totalNum',
      format(val) {
        return formatNumberWithMoney(val) ?? 0;
      },
    },
  ]);

  const sortProps = ['promotion_num'];

  /** 表格列排序 */
  const sortChangeHandel = ({ prop, order }: { prop: string; order: 'ascending' | 'descending' | null }) => {
    if (sortProps.includes(prop)) {
      filterData.value.column = prop;
      if (order === 'ascending') {
        filterData.value.asc = 'true';
      } else if (order === 'descending') {
        filterData.value.asc = 'false';
      } else {
        filterData.value.column = '';
        filterData.value.asc = 'false';
      }
      getAxiosData(true);
    } else {
      filterData.value.column = '';
      filterData.value.asc = 'false';
    }
  };
</script>

<style lang="scss" scoped>
  .pagination-box {
    @include flex(row, nowrap, center, center, center);
    padding-top: 15px;
  }

  .head-box {
    @include flex(row, nowrap, flex-start, center, center);

    .left-box {
      display: flex;
      flex: 1;
      flex-wrap: wrap;
      // grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
      // grid-gap: 15px;
      gap: 14px;
      // display: grid;
      align-items: center;
      margin-right: 15px;
    }
  }

  .page-contnet {
    display: flex;
    flex-direction: column;
    height: 100%;
  }

  .content-wrap {
    white-space: wrap;
  }
</style>
